package cn.itcast.naitang.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.controller.IpBean;
import cn.itcast.naitang.dto.CaoqiuGoodsList;
import cn.itcast.naitang.dto.CaoqiuOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 昆仑
 */
@RestController
@Slf4j
public class NaiTangController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<String> tokenList=new ArrayList<>();
    public  static volatile Map<String,IpBean> ret=new HashMap<>();
    @RequestMapping("/createNtMarket")
    public String createCmMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                    for(int z=0;z<tokenList.size();z++){
                        Proxy proxy=null;
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(1000);
                    }

            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####草球执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,String token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####获取商品数据异常####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,String token,String goodsId,String salePrice) throws InterruptedException {
        String result=null;
        try{
            result = HttpRequest.post("http://client.zgys.shop/api/ipTrade/goods/list?sidx=t1.for_sale_price&order=asc&goodsId="+goodsId+"&curPage=1&limit=100&sn=")
                    .setReadTimeout(5000)
                    .execute().body();
        }catch (Exception e){
            log.info("####请求商品数据异常######"+e.getMessage()+"####"+result);
        }
        if(!StringUtils.isEmpty(result)){
            CaoqiuGoodsList
                    caoqiuGoodsList= JSONUtil.toBean(result, CaoqiuGoodsList.class);
            log.info("######获取商品数据成功#######"+caoqiuGoodsList.toString()+"##商品id###"+goodsId);
            if(caoqiuGoodsList.getData()!=null && !CollectionUtils.isEmpty(caoqiuGoodsList.getData().getData())){
                List<CaoqiuGoodsList.CaoqiuGoodsDetailList> list=caoqiuGoodsList.getData().getData();
                for(CaoqiuGoodsList.CaoqiuGoodsDetailList detailDTO:list){
                    if(new BigDecimal(detailDTO.getGoods_price()).compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
//                        ThreadUtil.execAsync(() -> {
//                            saveOrder(finalProxy,token,detailDTO,goodsId);
//                        });
                        saveOrder(finalProxy,token,detailDTO,goodsId);
                        Thread.sleep(1100);
                    }

                }
            }
        }else{
            log.info("##获取商品数据异常##");
        }
    }

    public void saveOrder(Proxy proxy, String token, CaoqiuGoodsList.CaoqiuGoodsDetailList detailDTO, String goodsId){

        String createResult=null;
        try {
            JSONObject jsonObject = new JSONObject();;
            jsonObject.putOnce("buyNumber",1);
            jsonObject.putOnce("collectForSaleId",goodsId);
            jsonObject.putOnce("goods_id",goodsId);
            createResult =
                    HttpRequest.post("http://client.zgys.shop/api/seckill/createTradeOrder").body(jsonObject.toString()).header("","").header("Token",token).execute().body();
            CaoqiuOrder caoqiuOrder= JSONUtil.toBean(createResult, CaoqiuOrder.class);
            log.info("####支付结果######"+caoqiuOrder.toString());
            if(caoqiuOrder!=null && caoqiuOrder.getCode() ==1){

                log.info("####支付结果######"+caoqiuOrder.toString());
            }
        } catch (Exception e) {
            log.info("####支付结果异常######"+e.getMessage()+":detailDTO"+detailDTO.toString());
        }
    }
    public void addToken(){
        tokenList.add("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaDUuY2FvcWl1LnZpcFwvIiwiYXVkIjoiaHR0cHM6XC9cL2g1LmNhb3FpdS52aXBcLyIsImlhdCI6MTY4NjEwMjg2MiwibmJmIjoxNjg2MTAyODYyLCJleHAiOjE2ODYxODkyNjIsIm1lbWJlcl9pbmZvIjo0NjM0OX0.yMQn1VLDK0glZwRQNLmfOd1jItRaoVrdLuIcHSw23iE");
    }

    

}
